<?php
class Default_Model_Upgrade_Core  {
    /**
     * source table
     * @var string
     */
    protected $_table='';
    /**
     * target table
     * @var array
     */
    protected $_targetTable = array();

    protected $_upgradeLogPath='';
    /**
     *  cache file name
     * @var string
     */
    protected $_cacheFile;

    protected $_sfs3Pdo;

    protected $_newdbPdo;


    function __construct($table='')
    {

        if ($table)
        $this->_table = $table;
        $this->_upgradeLogPath = Bootstrap::getPath('data').'/upgrade';
        if (!is_dir($this->_upgradeLogPath))
        mkdir($this->_upgradeLogPath,0700);
        $this->_cacheFile = $this->_upgradeLogPath.'/'.$this->_table;
        $this->rawDbLink();
    }

    function fromArray($tableName,$arr) {
        if (!is_array($arr))
            throw new Zend_Exception('不正確的陣列格式');
        $query  = "INSERT INTO  $tableName  (".implode(',',array_keys($arr)).") VALUES('".implode("','",array_values($arr))."')";
        $this->_newdbPdo->exec($query) or die($query);
         return $this->_newdbPdo->lastInsertId();
    }

    /**
     * 建立資料庫連結,不透過 zend_dbmysql_select_db($arr['dbname'],$this->_sfs3DbLink);
     * @return unknown_type
     */

    function rawDbLink()
    {
        $str = file_get_contents(Bootstrap::getPath('data').'/sfs3dbset');

        $arr = unserialize($str);

        $dns = 'mysql:dbname='.$arr['dbname'].";host=".$arr['host'];
        $this->_sfs3Pdo = new PDO($dns,  $arr['username'],  $arr['password']);
        $dsnurl =  Bootstrap::$config['doctrine']['connection_string'];
        $arr = parse_url($dsnurl);
        //$arr = Bootstrap::$config['resources']['db']['params'];
        $dns = 'mysql:dbname='. substr($arr['path'],1) .";host=".$arr['host'];
        $this->_newdbPdo = new PDO($dns,  $arr['user'],  $arr['pass']);
        $this->_newdbPdo->query('SET NAMES UTF8');


    }

    /**
     * 檢查是否升級完成
     *
     */
    function isUpgrade()
    {
        $result = false;
        if (is_file($this->_cacheFile)){
            $up_arr = unserialize(file_get_contents($this->_cacheFile));
            //		if ($up_arr['error_count']==0)
            $result = true;
        }
        return $result;
    }

    /**
     * 升級的table
     * @return string
     */
    function getTableName()
    {
        return $this->_table;
    }

    /**
     * 升級後的 table
     * @return string|array
     */
    function getTargetTable()
    {
        return $this->_targetTable;
    }

    function getTargetTableRows()
    {
        $arr = array();
        foreach ($this->_targetTable as $tableName) {
            $sql = "SELECT COUNT(*)  AS rows FROM $tableName";
            $res = $this->_newdbPdo->query($sql)->fetch();
            $arr[$tableName] = $res['rows'];
        }
        return $arr;
    }

    /**
     *  Big5 to Utf8
     * @param $data
     * @return unknown_type
     */
    function iconv($data)
    {
        return  addslashes(iconv("Big5", "utf-8//IGNORE", $data));
    }

    function finishUpgrade($arr)
    {

        file_put_contents($this->_cacheFile,serialize($arr));
    }

}